# @Time    : 2025-07-17 14:46
# @Author  : strip
# @File    : response.py
# @Desc    : Response

from typing import Any
from fastapi.responses import ORJSONResponse
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

class Default(BaseModel):
    code: int
    message: str | None = None

def success_response(data: Any = None, kwargs: dict = None) -> ORJSONResponse:
    """ 成功响应，HTTP 状态码默认为 200，自动处理 ORM 对象序列化，支持扩展字段 """
    response_data = {'code': 200, 'message': '成功 | Success'}
    if data is not None:
        response_data['data'] = jsonable_encoder(data)
    if kwargs:
        response_data.update(kwargs)
    return ORJSONResponse(response_data)


def error_response(code: int, message: str, error: Any = None, kwargs: dict = None) -> ORJSONResponse:
    """
    一个更通用的错误响应函数，支持扩展字段，自动序列化 error
    :param code: HTTP 状态码 (也作为业务码)
    :param message: 错误类别消息
    :param error: 详细错误信息
    :param kwargs: 额外扩展字段
    :return: JSONResponse
    """
    response_data = {'code': code, 'message': message}
    if error:
        response_data['error'] = jsonable_encoder(error)
    if kwargs:
        response_data.update(kwargs)
    return ORJSONResponse(content=response_data, status_code=code)

def parameter_error_response(error: Any = None, kwargs: dict = None) -> ORJSONResponse:
    return error_response(code=400, message='参数错误 | Bad Request', error=error, kwargs=kwargs)

def server_error_response(error: Any = None, kwargs: dict = None) -> ORJSONResponse:
    return error_response(code=500, message='服务器错误 | Internal Server Error', error=error, kwargs=kwargs)


__all__ = ['success_response', 'parameter_error_response', 'server_error_response', 'Default']